<!DOCTYPE html>
<html lang="en" xmlns:th="https://www.thymeleaf.org"
      xmlns:sec="http://www.thymeleaf.org/extras/spring-security">
<div th:replace="common/common::html"></div>
<head>
    <meta charset="UTF-8">
    <link th:href="@{/assets/css/page.css}" rel="stylesheet"/>
    <title th:text="#{file.manger.title}">title</title>
    <script th:inline="javascript">
        const FILE_TYPE_FILE = 0
        const FILE_TYPE_FOLDER = 1
        var _gridWidth;
        var _gridHeight;
        //页面自适应
        function resizePageSize(){
            _gridWidth = $(document).width()-12;/*  -189 是去掉左侧 菜单的宽度，   -12 是防止浏览器缩小页面 出现滚动条 恢复页面时  折行的问题 */
            _gridHeight = $(document).height()-65 -40; /* -32 顶部主菜单高度，   -90 查询条件高度*/
        }

        $(function () {
            resizePageSize();
            var _columnWidth = (_gridWidth-150)/4;
            $("#flexigrid-id").flexigrid({
                width : _gridWidth,
                height : _gridHeight,
                url : /*[[@{/file/queryFileInfoListByPage}]]*/"",
                dataType : 'json',
                colModel : [
                    {display : 'fileUuid',name : 'fileUuid',width : 150,sortable : false,align : 'center',hide : 'true'},
                    {display : /*[[#{file.name}]]*/"",name : 'fileName',width : _columnWidth, sortable : true,align : 'center',
                        process:function (v,_trid,_row){
                            var html = `<div style="display: flex; width: 100px">`
                            if(_row.fileType === FILE_TYPE_FOLDER){
                                html += `<a href="#" style="color: #f7ba2a" class="btn" onclick="enterDir('${_row.fileUuid}', '${_row.filePath}')"><i class="glyphicon glyphicon-folder-close" style="margin-right: 5px"></i><span>${v}</span></a>`

                            }else{
                                html += `<a href="#" style="color: #00b1ef" class="btn" onclick="preFile ('${_row.fileUuid}', '${v}')"><i class="glyphicon glyphicon-folder-close" style="margin-right: 5px"></i><span>${v}</span></a>`
                            }
                            html +=`</div>`
                            return html;
                        }
                    },
                    {display : /*[[#{file.size}]]*/"",name : 'fileCapacity',width : _columnWidth, sortable : true,align : 'center'},
                    {display : /*[[#{file.last.time}]]*/"",name : 'modtime',width : _columnWidth, sortable : true,align : 'center'},
                    {display : /*[[#{common.operation}]]*/"",name : 'fileUuid',width : _columnWidth, sortable : true,align : 'center',process:function (v,_trid,_row){
                            var html = `<div>`
                            if([[${#authorization.expression("hasRole('ROLE_cldk_data_user_mod')")}]]) {
                                html += `<a href="#" class="btn" onclick="modifyUserInfo('${v}')" title=[[#{common.modify}]]><i class="glyphicon glyphicon-pencil"></i></a>`
                            }
                            // 权限设置按钮（仅有权限的用户可见）
                              {
                                html += `<a href="#" class="btn" onclick="bathAllocateRote('${v}')" title=[[#{file.acl.set}]]><i class="glyphicon glyphicon-share"></i></a>`
                            }
                                var url=/*[[@{/file/downFile}]]*/'';
                                url+="/"+v;{
                                html += `<a href=${url} class="btn" " title=[[#{file.download.btn}]] target="_blank"><i class="glyphicon glyphicon-download"></i></a>`
                            }
                            // 新增分享按钮：调用shareFile函数，传递fileUuid和filePath（即obsKey）
                            html += `<a href="#" class="btn" onclick="shareFile('${v}', '${_row.filePath}')" title="分享"><i class="glyphicon glyphicon-share-alt"></i></a>`
                            html +=`<div>`
                            return html;
                        }
                    },
                ],
                resizable : false, //resizable table是否可伸缩
                useRp : true,
                usepager : true, //是否分页
                autoload : false, //自动加载，即第一次发起ajax请求
                hideOnSubmit : true, //是否在回调时显示遮盖
                showcheckbox : true, //是否显示多选框
                //rowhandler : rowDbclick, //是否启用行的扩展事情功能,在生成行时绑定事件，如双击，右键等
                rowbinddata : true
            });
            query();

            $("#mkdir-dialog-id").dialog({
                autoOpen : false,
                width : 400,
                modal : true,
                resizable : false,
                title: /*[[#{file.mkdir.dialog.tip}]]*/'',
                buttons: [
                    {
                        text: /*[[#{common.confirm}]]*/'',
                        click: function() {
                            var parentId = $("#file-folder-id").attr("parent-id")
                            var flag = $("#file-folder-name-id").checkDom();
                            if (!flag){
                                return
                            }
                            var folderName = $("#file-folder-name-id").val();
                            $.ajax({
                                type: 'post',
                                async: false,
                                dataType : 'json',
                                url: /*[[@{/file/mkdirFileInfo}]]*/'',
                                data: [
                                    {name:"parentId",value:parentId},
                                    {name: "folderName", value: folderName}
                                ],
                                success: function (data) {
                                    message(data.msg)
                                    query()
                                    $("#file-folder-name-id").val('')
                                    $("#mkdir-dialog-id").dialog('close')
                                },
                                error: function(msg){
                                    message(/*[[#{common.error}]]*/'')
                                }
                            });
                        }
                    },
                    {
                        text: /*[[#{common.cancel}]]*/'',
                        click: function() {
                            $( this ).dialog( "close" );
                        }
                    }
                ]
            })

            $("#upload-file-dialog-id").dialog({
                autoOpen : false,
                width : 400,
                modal : true,
                resizable : false,
                title: /*[[#{file.upload.dialog.tip}]]*/'',
                buttons: [
                    {
                        text: /*[[#{common.confirm}]]*/'',
                        click: function() {
                            var flag = $("#upload-file-name-id").checkDom()
                            if(!flag){
                                return
                            }
                            $("#upload-file-form-id").submit()
                        }
                    },
                    {
                        text: /*[[#{common.cancel}]]*/'',
                        click: function() {
                            $( this ).dialog( "close" );
                        }
                    }
                ]
            })


            $("#upload-file-form-id").ajaxForm({
                dataType: "json",
                success : function(data) {
                    query();
                    $("#upload-file-dialog-id").dialog('close')
                },
                error : function() {
                    message(/*[[#{common.error}]]*/'');
                },
            })

            //分配权限
            $("#acl-dialog-id").dialog({
                autoOpen : false,
                width : 400,
                modal : true,
                resizable : false,
                title: /*[[#{file.allocat.role.dialog}]]*/'',
                buttons: [
                    {
                        text: /*[[#{common.confirm}]]*/'',
                        click: function() {

                        }
                    },//end button
                    {
                        text: /*[[#{common.cancel}]]*/'',
                        click: function() {
                            $( this ).dialog( "close" );
                        }
                    }//end buttons
                ]

            })

                // 文件浏览
            $("#pre-document-dialog-id").dialog({
                autoOpen : false,
                width : 800,
                modal : true,
                resizable : false,
                title: /*[[#{file.upload.dialog.tip}]]*/'',
                buttons: [
                    {
                        text: /*[[#{common.confirm}]]*/'',
                        click: function() {
                            $(this).dialog("close");
                        }
                    },
                 ]
            })

        });

        /**
         * 文件同步
         */
        function syncFileData() {
            $.ajax({
                type: 'post',
                async: false,
                dataType : 'json',
                url: /*[[@{/file/syncFileData}]]*/'',
                data: [],
                success: function (data) {
                    message(data.msg)
                },
                error: function(msg){
                    message(/*[[#{common.error}]]*/'');
                }
            });
        }

        /**
         * 表格查询
         */
        function query(){

            var parentId = $("#file-folder-id").attr("parent-id")

            $("#flexigrid-id").flexOptions({
                extParam:[
                    {name:"parentId", value:parentId}
                ]

            }).flexReload()
        }

        function enterDir(fileUuid, filePath) {
            /*alert("进入文件夹：" + fileUuid)*/
            $("#file-folder-id").attr("parent-id", fileUuid)
            if (fileUuid === -1){
                $("#file-folder-id").val("/")
            }
            $.ajax({
                type: 'post',
                async: false,
                dataType : 'json',
                url: /*[[@{/file/queryFileInfoById}]]*/'',
                data: [
                    {name:"fileUuid",value:fileUuid}
                ],
                success: function (data) {
                    if (data){
                        $("#file-folder-id").val(data['filePath'])

                    }else{
                        $("#file-folder-id").val("/")
                    }
                },
                error: function(msg){
                    message(/*[[#{common.error}]]*/'');
                }
            });

            query()
        }

        function upDir() {
            var fileUuid = $("#file-folder-id").attr("parent-id")
            $.ajax({
                type: 'post',
                async: false,
                dataType : 'json',
                url: /*[[@{/file/queryFileInfoById}]]*/'',
                data: [
                    {name:"fileUuid",value:fileUuid}
                ],
                success: function (data) {
                   if (data){
                       enterDir(data['parentUuid'])

                   }else{
                       $("#file-folder-id").val("/")
                   }
                },
                error: function(msg){
                    message(/*[[#{common.error}]]*/'');
                }
            });
        }

        function mkdirFun() {
            $("#mkdir-dialog-id").dialog('open')

        }
        /*
        *上传文件
        * */
        function uploadFile() {
            $("#upload-file-parent-id").val($("#file-folder-id").attr("parent-id"));
            $("#upload-file-dialog-id").dialog('open')
        }
        /*
       *文件复制
       * */
        function copyFile() {
            var ids = $("#flexigrid-id").getFlexigridiAttrByIndex(0)
            if (ids.length === 0) {
                message(/*[[#{common.empty}]]*/'');
                return;
            }
            $("#file-copy-btn-id").attr('ids', ids)
            var parentId = $("#file-folder-id").attr("parent-id")
            $("#file-copy-btn-id").attr('src-uuid', parentId)

            $("#file-past-btn-id").removeClass('hidden')
            $("#file-past-num-id").text(ids.length+"")
        }

        // 权限树配置
        var aclSetting = {
            check: {
                enable: true, // 启用勾选功能
                chkboxType: { "Y": "p", "N": "s" } // 勾选父子节点关联规则
            },
            data: {
                simpleData: {
                    enable: true // 启用简单数据格式（id/pId）
                }
            }
        };



        // 分享文件：发送请求获取临时链接并展示
        function shareFile(fileUuid, obsKey) {
            // 发送AJAX请求到后端接口，获取临时分享链接
            $.ajax({
                type: 'post',
                url: /*[[@{/file/generateShareUrl}]]*/'', // 后端接口地址
                data: {
                    "fileUuid": fileUuid,
                    "obsKey": obsKey // OBS中的文件标识（如"a4.jpg"）
                },
                dataType: 'json',
                success: function (data) {
                    if (data.success) {
                        // 展示分享链接（如弹出对话框）
                        alert("分享链接：" + data.shareUrl + "\n有效期：1小时");
                        // 可选：复制链接到剪贴板
                        navigator.clipboard.writeText(data.shareUrl).then(() => {
                            alert("链接已复制到剪贴板");
                        });
                    } else {
                        message(data.msg); // 错误提示
                    }
                },
                error: function () {
                    message("生成分享链接失败");
                }
            });



            $("#file-past-btn-id").removeClass('hidden')
            $("#file-past-num-id").text(ids.length+"")
        }
        /*
       *文件粘贴
       * */
        function pasteFile() {
            //$("#file-copy-btn-id").attr('ids', ids)
            var parentId = $("#file-folder-id").attr("parent-id");
            var srcUuid = $("#file-copy-btn-id").attr('src-uuid')
            if(parentId === srcUuid){
                message(/*[[#{file.paste.fail.folder}]]*/"")
                return
            }
            var ids = $("#file-copy-btn-id").attr('ids')
            $.ajax({
                type: 'post',
                async: false,
                dataType : 'json',
                url: /*[[@{/file/copyFile}]]*/'',
                data: [
                    {name:"srcUuidList",value:ids},
                    {name:"parentId",value:parentId},
                ],
                success: function (data) {
                    /*if (data){
                        enterDir(data['parentUuid'])

                    }else{
                        $("#file-folder-id").val("/")
                    }*/
                    message(data.msg)
                    if (data.success){
                        $("#file-past-btn-id").addClass("hidden");
                    }
                },
                error: function(msg){
                    message(/*[[#{common.error}]]*/'');
                }
            });
        }

        // 权限树配置
        var aclSetting = {
            check: {
                enable: true, // 启用勾选功能
                chkboxType: { "Y": "p", "N": "s" } // 勾选父子节点关联规则
            },
            data: {
                simpleData: {
                    enable: true // 启用简单数据格式（id/pId）
                }
            }
        };

        // 打开权限设置对话框
        function openAclDialog(fileUuid) {
            $("#acl-file-uuid").val(fileUuid); // 记录当前文件ID
            // 1. 查询文件当前权限
            $.ajax({
                type: 'post',
                dataType: 'json',
                url: /*[[@{/file/queryFileAcl}]]*/'',
                data: [{name: "fileUuid", value: fileUuid}],
                success: function (ztreeData) {
                    // 2. 初始化权限树
                    $.fn.zTree.init($("#acl-ztree-id"), aclSetting, ztreeData);
                    // 3. 打开对话框
                    $("#acl-dialog-id").dialog({
                        autoOpen: false,
                        width: 400,
                        modal: true,
                        resizable: false,
                        title: /*[[#{file.acl.dialog.title}]]*/'',
                        buttons: [
                            {
                                text: /*[[#{common.confirm}]]*/'',
                                click: function () {
                                    saveAcl(); // 保存权限设置
                                }
                            },
                            {
                                text: /*[[#{common.cancel}]]*/'',
                                click: function () {
                                    $(this).dialog("close");
                                }
                            }
                        ]
                    }).dialog("open");
                },
                error: function () {
                    message(/*[[#{file.acl.query.fail}]]*/'');
                }
            });
        }

        // 保存权限设置
        function saveAcl() {
            var fileUuid = $("#acl-file-uuid").val();
            // 1. 获取选中的权限节点
            var zTree = $.fn.zTree.getZTreeObj("acl-ztree-id");
            var checkedNodes = zTree.getCheckedNodes(true);
            var aclArray = [];
            for (var i = 0; i < checkedNodes.length; i++) {
                aclArray.push(checkedNodes[i].id); // 收集权限标识（如"READ"、"WRITE"）
            }
            // 2. 调用后端接口保存权限
            $.ajax({
                type: 'post',
                dataType: 'json',
                url: /*[[@{/file/setFileAcl}]]*/'',
                data: [
                    {name: "fileUuid", value: fileUuid},
                    {name: "aclArray", value: aclArray.join(",")}
                ],
                success: function (data) {
                    message(data.msg);
                    if (data.success) {
                        $("#acl-dialog-id").dialog("close");
                        query(); // 刷新文件列表
                    }
                },
                error: function () {
                    message(/*[[#{file.acl.set.fail}]]*/'');
                }
            });
        }

        var allocateSetting = {
            check: {
                enable: true
            },
            data: {
                simpleData: {
                    enable: true
                }
            }
        };

        // 方案1：使用数据属性存储国际化内容（推荐，兼容性好）
        function bathAllocateRote() {
            var ids = $("#flexigrid-id").getFlexigridiAttrByIndex(0);
            if(ids.length === 0){
                message(/*[[#{common.empty}]]*/'');
                return;
            }

            var data = [
                {id:'100',name:"桶读权限",pId:'-1',checked:false,open:true},
                {id:'200',name:"桶写权限",pId:'-1',checked:false,open:true},
                {id:'300',name:"ACL读权限",pId:'-1',checked:false,open:true},
                {id:'400',name:"ACL写权限",pId:'-1',checked:false,open:true},
            ];

            $("#acl-dialog-id").attr('ids',ids);
            $.fn.zTree.init($('#acl-ztree-id'),allocateSetting,data);

            // 在页面中提前定义隐藏的国际化文本容器
            if ($("#i18n-container").length === 0) {
                $("body").append(`
        <div id="i18n-container" style="display:none">
            <span id="msg_success">[[#{file.permission.allocate.success}]]</span>
            <span id="title_success">[[#{operation.success}]]</span>
        </div>
    `);
            }

            $("#acl-dialog-id").dialog({
                autoOpen: false,
                modal: true,
                buttons: {
                    "确认": function() {
                        $(this).dialog("close");

                        // 从隐藏容器中获取国际化内容并移除引号
                        var successMsg = $("#msg_success").text()
                            .replace(/^["']/, '') // 移除开头的单引号或双引号
                            .replace(/["']$/, ''); // 移除结尾的单引号或双引号

                        var successTitle = $("#title_success").text()
                            .replace(/^["']/, '')
                            .replace(/["']$/, '');

                        $("<div>" + successMsg + "</div>").dialog({
                            title: successTitle,
                            modal: true,
                            buttons: {
                                "确定": function() {
                                    $(this).dialog("close");
                                }
                            },
                            close: function() {
                                $(this).remove();
                            }
                        });
                    },
                    "取消": function() {
                        $(this).dialog("close");
                    }
                }
            }).dialog('open');
        }

        /**
         * 文件预览
         * @param fileUuidp
         * @param fileName
         */
        function preFile(fileUuid,fileName) {
            alert(fileName)
            var regDoc = new RegExp("^.*docx$")
            var regImage = new RegExp("^.*\png$");
            if(regDoc.test(fileName)){
                $.ajax({
                    type: 'post',
                    async: false,
                    dataType : 'json',
                    url: /*[[@{/file/getShareUrl}]]*/'',
                    data: [
                        {name:"fileUuid",value:fileUuid}

                    ],
                    success: function (data) {
                        console.info("preFile:" + JSON.stringify(data))
                        var url = data['code'];
                        if(url){
                            url=url.replaceAll("&","%26")
                            url=url.replaceAll("？","%26")
                            $("#pro-document-iframe-id").attr("src","https://view.xdocin.com/xdoc?_xdoc="+ url)
                        }
                        $("#pre-document-dialog-id").dialog('option','title');
                        $("#pre-document-dialog-id").dialog('open')
                    },
                    error: function(msg){
                        message(/*[[#{common.error}]]*/'');
                    }
                });
            }else if (regImage.test(fileName)) {
                // 图片预览逻辑
                // 获取图片访问URL（假设后端提供专门的图片访问接口）
                var imageUrl = /*[[@{/file/getImage}]]*/'' + "?fileUuid=" + fileUuid;

                // 创建图片预览对话框内容
                var imgHtml = '<img src="' + imageUrl + '" style="max-width: 90%; max-height: 80vh; display: block; margin: 0 auto;">';

                // 显示图片预览对话框（可复用现有对话框或新建）
                $("#pre-image-dialog-id").html(imgHtml);
                $("#pre-image-dialog-id").dialog({
                    title: fileName,
                    modal: true,
                    width: "80%",
                    height: "auto",
                    close: function() {
                        $(this).empty(); // 关闭时清空内容
                    }
                }).dialog('open');
            } else {
                // 其他文件类型提示
                alert("暂不支持该类型文件预览");
            }
        }

    </script>
    <style>
        a.hidden{
            display: none;
        }
        #file-past-num-id{
            color: #ff0000;
        }
    </style>
</head>
<body >
    <header>


        <a href="#" class="btn-info btn" onclick="upDir()" th:title="#{file.up.folder}">
            <i class="glyphicon glyphicon-open"></i>
        </a>

        <input id="file-folder-id" value="/" parent-id="-1">

        <a href="#" class="btn-info btn" onclick="syncFileData()">
            <i class="glyphicon glyphicon-refresh"></i>
            <span th:text="#{file.sync.data}"></span>
        </a>

        <a href="#" class="btn-info btn" onclick="mkdirFun()">
            <i class="glyphicon glyphicon-book"></i>
            <span th:text="#{file.mkdir}"></span>
        </a>

        <a href="#" class="btn-info btn" onclick="uploadFile()">
            <i class="glyphicon glyphicon-cloud-upload"></i>
            <span th:text="#{file.upload.btn}"></span>
        </a>

        <a id="file-copy-btn-id" href="#" class="btn-info btn" onclick="copyFile()">
            <i class="glyphicon glyphicon-copy"></i>
            <span th:text="#{file.copy.btn}"></span>
        </a>

        <a id="file-past-btn-id" href="#" class="btn-info btn hidden" onclick="pasteFile()">
            <i class="glyphicon glyphicon-paste"></i>
            <span th:text="#{file.paste.btn}"></span>
            (
            <span id="file-past-num-id"></span>
            )
        </a>
        <a href="#" sec:authorize="hasRole('ROLE_cldk_data_user_role')"  class="btn-info btn" onclick="bathAllocateRote()">
            <i class="glyphicon glyphicon-share"></i>
            <span th:text="#{user.allocate.file}"></span>
        </a>


    </header>

    <table id="flexigrid-id"></table>

    <div id="mkdir-dialog-id" style="display: none">
        <div class="form-group">
            <span th:text="#{file.folder.name}"></span>
            <input id="file-folder-name-id" class="form-control" pattern="^.+$">
        </div>
    </div>


    <div id="upload-file-dialog-id" style="display: none">
        <form id="upload-file-form-id" enctype="multipart/form-data" method="post" th:action="@{/file/uploadFile}">
            <input name="parentId" id="upload-file-parent-id" type="hidden">
            <div class="form-group">
                <span th:text="#{file.name}"></span>
                <input name="fileName" id="upload-file-name-id" pattern="^.+$" type="file">
            </div>
        </form>
    </div>

    <div id="pre-document-dialog-id" style="display: none">
        <iframe id="pro-document-iframe-id" style="width: 100%;height:400px ">

        </iframe>
    </div>
    <!-- 权限设置对话框 -->
    <div id="acl-dialog-id" style="display: none">
        <input type="hidden" id="acl-file-uuid" value=""> <!-- 存储当前操作的文件ID -->
        <ul id="acl-ztree-id" class="ztree" style="height: 100px; overflow-y: auto;"></ul>
    </div>
    <div id="pre-image-dialog-id" style="display: none;"></div>
</body>
</html>